#include "proxydesc.h"

int ProxyDesc::count=0;

ProxyDesc::ProxyDesc( ProxyType type,
           const QString & hostName,
           quint16 port,
           const QString & user,
           const QString & password)
               :QNetworkProxy (type, hostName, port, user, password){
    changed=TRUE;
    _status=PENDING;
    _index=count++;

};

void ProxyDesc::wait(QString service, QTime time ){
    changed=TRUE;
    waitMap.insert(service, time);
};
bool ProxyDesc::canDownload(QString hostService){
    //check time of all locks
    foreach(QString srv, waitMap.keys()){
        if(waitMap[hostService]<QTime::currentTime()){
            waitMap.remove(srv);
            changed=TRUE;
        }
    }
    return !waitMap.contains(hostService);
};

void ProxyDesc::setStatus(int stt){
    if(stt!=_status){
        changed=TRUE;
        _status=stt;
    }
}

int ProxyDesc::status(){
    return _status;
}
int ProxyDesc::index(){
    return _index;
};

QDomElement ProxyDesc::xmlDesc(QDomDocument* doc){
    changed=FALSE;
    QDomElement mainTag=doc->createElement("proxy");
    (mainTag.appendChild(doc->createElement("index")).appendChild(doc->createTextNode(QString().number(_index))));
    (mainTag.appendChild(doc->createElement("type")).appendChild(doc->createTextNode(QString().number(type()))));
    (mainTag.appendChild(doc->createElement("host")).appendChild(doc->createTextNode(hostName())));
    (mainTag.appendChild(doc->createElement("port")).appendChild(doc->createTextNode(QString().number(port()))));
    (mainTag.appendChild(doc->createElement("status")).appendChild(doc->createTextNode(QString().number(_status))));
    if(!waitMap.isEmpty()){
        QDomElement waits=doc->createElement("waits");
        QMap<QString, QTime>::iterator i;
        for (i = waitMap.begin(); i != waitMap.end(); ++i){
            QDomElement wait=doc->createElement("wait");
            wait.appendChild(doc->createElement("site")).appendChild(doc->createTextNode(i.key()));
            wait.appendChild(doc->createElement("time")).appendChild(doc->createTextNode(QTime(i.value()).toString()));
            //cout << i.key() << ": " << i.value() << endl;
            waits.appendChild(wait);
        }

        mainTag.appendChild(waits);
    }
    return mainTag;
}


